<?php


namespace App\Services\Configs;


use App\Models\ImThirdPartyConfigs;

class DefaultService
{
    const HUANXIN_IM = 'huanxin_im';//环信即时通讯
    const NETEASE_IM = 'netease_im';//网易云信即时通讯
    const RONGYUN_IM = 'rong_cloud_im';//融云即时通讯
    const ALI_OSS = 'ali_oss';//阿里云存储
    const TENCENT_OSS = 'tencent_oss';//腾讯云存储
    const ALI_LIVE = 'ali_live';//阿里云直播
    const TENCENT_LIVE = 'tencent_live';//腾讯云直播
    const AGORA_AV = 'agora_av';//声网音视频
    const ALI_AV = 'ali_av';//阿里云音视频
    const ALI_IDENTIFY = 'ali_idcard';//阿里云身份认证
    const ALI_SMS = 'ali_sms';//阿里云短信

    //初始话配置信息
    public function init()
    {
        $configs = require_once(dirname(__FILE__) . '/data/default.php');
        if (!empty($configs)) {
            foreach ($configs as $key => $config) {
                $title = '';
                if (isset($config['selfTitle'])) {
                    $title = $config['selfTitle'];
                }
                $count = ImThirdPartyConfigs::where('key', $key)->count();
                if (!$count) {
                    $tpConfig = new ImThirdPartyConfigs();
                    $tpConfig->title = $title;
                    $tpConfig->key = $key;
                    $tpConfig->value = json_encode($config);
                    $tpConfig->save();
                }
            }
        }
    }

    /**
     * 设置配置项
     * @param $key 键
     * @param $value 值
     * @param $title 标题
     */
    public function set($key, $value, $title = null)
    {
        $config = ImThirdPartyConfigs::where('key', $key)->first();
        if (!$config) {
            $config = new ImThirdPartyConfigs();
        }
        if (is_array($value)) {
            $value = json_encode($value);
        }
        $config->key = $key;
        $config->value = $value;
        if (isset($title)) {
            $config->title = $title;
        }
        $config->save();
    }

    /**
     * 获取指定配置
     * @param $key
     * @return mixed
     */
    public function first($key)
    {
        $config = ImThirdPartyConfigs::where('key', $key)
            ->where('status', 1)
            ->first();
        if ($config) {
            $config = $config->value;
        }
        return $config;
    }

    /**
     * 获取第三方配置
     * 可根据 key 查找
     * @param array $keys 键
     * @param string $searchWord 搜素词
     * @return mixed
     */
    public function get($keys = [], $searchWord = null)
    {
        $query = new ImThirdPartyConfigs();
        $query = $query->with('operator');
        if (!empty($keys)) {
            $query = $query->whereIn('key', $keys);
        }
        if (isset($searchWord)) {
            $query = $query->where(function ($sql) use ($searchWord) {
                $sql->where('key', 'like', $searchWord . '%');
                $sql->orWhere('title', 'like', $searchWord . '%');
            });
        }
        $configs = $query->get();
        return $configs;
    }
}
